package com.electromagnetic.industry.software.manage.service.serviceimpl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.electromagnetic.industry.software.manage.service.FileSystemService;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;

@Service
public class FileSystemServiceImpl implements FileSystemService {

    @Override
    public void copyFile(String source, String destination) {
        if (source.equals(destination)) {
            return;
        }
        FileUtil.copy(source, destination, true);
    }

    /**
     * @param source      /user/aaa/bbb.txt
     * @param destination /user/bbb/aaa.txt
     */
    @Override
    public void moveFile(String source, String destination) {
        if (source.equals(destination)) {
            return;
        }
        String destParentDir = FileUtil.getParent(destination, 1);
        if (!FileUtil.exist(destParentDir)) {
            FileUtil.mkdir(destParentDir);
        }
        if (FileUtil.exist(destination)) {
            return;
        }
        FileUtil.move(new File(source), new File(destination), false);
    }

    @Override
    public void save(InputStream inputStream, String destination) {
        FileUtil.writeFromStream(inputStream, destination);
    }

    @Override
    public void renameFile(String sourcePath, String newName) {
        sourcePath = sourcePath.replace("//", "/");
        sourcePath = sourcePath.endsWith("/") ? sourcePath.substring(0, sourcePath.length() - 1) : sourcePath;
        FileUtil.rename(new File(sourcePath), newName, true);
    }

    @Override
    public void renameFile(String sourcePath, String oldName, String newName) {
        File sourceFile = new File(sourcePath + File.separator + oldName);
        FileUtil.rename(sourceFile, newName, true);
    }

    @Override
    public boolean writeStringToFile(String filePath, String contents) {
        FileUtil.writeString(contents, filePath, Charset.defaultCharset());
        return true;
    }

    @Override
    public boolean deleteFile(String... filePaths) {
        for (String filePath : filePaths) {
            FileUtil.del(filePath);
        }
        return false;
    }
}
